﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework;
using System.Configuration;
using System.Data.SqlClient;
using FantastPlatform.Decision.IService;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Framework.Model;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class PersonTaskService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IUserService userService = ServiceFactory.CreateService<IUserService>();
            IPatrolTaskService service = ServiceFactory.CreateService<IPatrolTaskService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Field = "Enable", Type = typeof(bool).FullName, Value1 = true };
            group.Conditions.Add(enableCondition);

            switch (Action)
            {
                case "GetPersonByOrgCode":
                    string policeCode = LoginEmployee.Code;
                    object[] obj = GetPersonByPoliceCode(policeCode);
                    ReturnList(obj.Length, obj);
                    break;
                case "GetPersonByTaskId":
                    IPatrolTask patrolTask = service.Get(Id);
                    IList<IEmployee> employees = patrolTask.Policemans;
                    obj = (from p in employees
                           select new
                           {
                               Id = p.Id,
                               Code = p.Code,
                               Name = p.Name
                           }).ToArray();
                    break;
                case "GetPolice":
                    IUser user = JsonToEntity<IUser>(Data);
                    int totalpolice = 0;
                    group.Conditions.Add(new Condition { Field = "Employees.EmployeePosts.Post.Organization.Name", Relation = Relations.And, Type = typeof(string).FullName, Comparison = Comparisons.Like, Value1 = "%派出所" });
                    if (!string.IsNullOrEmpty(user.Name))
                    {
                        Condition nameCodidton = new Condition() { Field = "Name", Type = typeof(string).FullName, Value1 = user.Name, Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(nameCodidton);
                    }
                    if (!string.IsNullOrEmpty(user.Code))
                    {
                        Condition codeCodidton = new Condition() { Field = "Code", Type = typeof(string).FullName, Value1 = user.Code, Comparison = Comparisons.Like, Relation = Relations.And };
                        group.Conditions.Add(codeCodidton);
                    }
                    IList<IUser> policelist = userService.Search(group, null, PageSize, 1, out totalpolice);

                    object[] objpolice = (from o in policelist
                                          select new
                                          {
                                              Id = o.Id,
                                              Code = o.Code,
                                              Name = o.Name
                                          }
                                     ).ToArray();
                    ReturnList(totalpolice, objpolice);
                    break;
                case "AddUser":
                    if (Id != 0&&string.IsNullOrEmpty(Data))
                    {
                        try
                        {
                            string[] Ids = Data.Split(',');
                            IPatrolTask task = service.Get(Convert.ToInt32(Id));
                            for (var i = 0; i < Ids.Length; i++)
                            {
                                task.Policemans.Add(new Employee() { Id = Convert.ToInt32(Ids[i]) });
                            }
                            service = ServiceFactory.CreateService<IPatrolTaskService>();
                            service.Update(task);
                            ReturnSuccessMessage("添加执勤人员成功");
                        }
                        catch (Exception ex)
                        {
                            ReturnErrorMessage("添加执勤人员失败！" + ex.Message);
                        }
                    }
                    break;
                case "RemoveUser":
                    if (Id != 0 && string.IsNullOrEmpty(Data))
                    {
                        try
                        {
                            string[] Ids = Data.Split(',');
                            IPatrolTask task = service.Get(Convert.ToInt32(Id));
                            IList<IEmployee> employeeList = task.Policemans;
                            for (var i = 0; i < Ids.Length; i++)
                            {
                                for(var j=0;j<employeeList.Count;j++)
                                {
                                    if (employeeList[j].ToString() == Ids[i])
                                    {
                                        task.Policemans.Remove(employeeList[j]);
                                        break;
                                    }
                                }
                            }
                            service = ServiceFactory.CreateService<IPatrolTaskService>();
                            service.Update(task);
                            ReturnSuccessMessage("添加执勤人员成功");
                        }
                        catch (Exception ex)
                        {
                            ReturnErrorMessage("添加执勤人员失败！" + ex.Message);
                        }
                    }
                    break;
            }
        }

        private object[] GetPersonByPoliceCode(string Code)
        {
            List<object> obj = new List<object>();
            string sql = "select u.id,u.number,u.[name] from dbo.[user] as u join dbo.[user] as u2 on u.UnitCode = u2.UnitCode where u2.Number = '" + Code + "'";
            string conStr = ConfigurationManager.AppSettings["Case"];
            try
            {
                SqlConnection con = new SqlConnection(conStr);
                SqlCommand command = new SqlCommand(sql, con);
                con.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    obj.Add(new
                    {
                        Id = reader[0].ToString(),
                        Code = reader[1].ToString(),
                        Name = reader[2].ToString()
                    });
                }
            }
            catch (Exception ex)
            {

            }
            return obj.ToArray();
        }
    }
}